﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using GaiNo.Core.Extensions;
using GaiNo.Core.Helpers;
using System.IO;
using System.Drawing.Imaging;
namespace GaiNo.Core.Services
{
    public abstract class AuthCode : IAuthCode
    {
        protected int _code_lenght = 4;
        protected Random rnd = new Random(unchecked((int)DateTime.Now.Ticks));
        const string _AUTHCODE_ = "_AUTHCODE_";
        string _code = string.Empty;
        protected string Code
        {
            get
            {
                if(_code.IsNullOrEmpty())
                    return SessionHelper.Get<string>(_AUTHCODE_);
                return _code;
            }
            set
            {
                SessionHelper.Set(_AUTHCODE_, value);
            }
        }
        #region IAuthCode 成员
        public byte[] Create()
        {
            //建立Bitmap对象，绘图
            Bitmap basemap = new Bitmap(160, 60);
            Graphics graph = Graphics.FromImage(basemap);
            graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 160, 60);
            Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
            string letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789";
            string letter;
            StringBuilder s = new StringBuilder();

            //添加随机字符
            for (int x = 0; x < 4; x++)
            {
                letter = letters.Substring(rnd.Next(0, letters.Length - 1), 1);
                s.Append(letter);
                graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, rnd.Next(0, 15));
            }
            Code = s.ToString();
            //混淆背景
            Pen linePen = new Pen(new SolidBrush(Color.Black), 2);
            for (int x = 0; x < 6; x++)
                graph.DrawLine(linePen, new Point(rnd.Next(0, 159), rnd.Next(0, 59)), new Point(rnd.Next(0, 159), rnd.Next(0, 59)));

            MemoryStream stream = new MemoryStream();
            basemap.Save(stream, ImageFormat.Jpeg);

            return stream.ToArray();
        }
        public virtual bool Check(object input)
        {
            bool result = false;
            try
            {
                result = SessionHelper.Get<string>(_AUTHCODE_).ToLower().Equals(input.ToString().ToLower());
                SessionHelper.Clear();
            }
            catch
            {
                result = false;
            }

            return result;
        }
        #endregion
    }
}
